package cn.zhagzheguo.xk.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.zhagzheguo.xk.dao.StudentDao;
import cn.zhagzheguo.xk.model.Student;
import cn.zhagzheguo.xk.status.LoginStatus;

@Controller
@RequestMapping("/stu")
public class StudentController {

	private Student curStu;

	@Autowired
	private StudentDao stuDao;

	@RequestMapping(value = "/login")
	public String login(HttpServletRequest request, ModelMap model, @RequestParam("stuid") String stuid,
			@RequestParam("pwd") String pwd) {
		System.out.println("stuid=" + stuid + ",pwd=" + pwd);
		Student stu = stuDao.getStuByStuId(stuid);
		if (stu == null) {
			System.out.println("no user.");
			model.addAttribute("loginMsg", LoginStatus.NO_USER);
			return "index.jsp";
		}

		if (stu.getPwd().equals(pwd)) {
			System.out.println("success");
			model.addAttribute("user", stu);
			request.getSession().setAttribute("user_id", stu);
			curStu = stu;
			return "list.jsp";
		} else {
			System.out.println("fail");
			model.addAttribute("loginMsg", LoginStatus.WRONG_PWD);
			return "index.jsp";
		}

	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) {

		Student stu = (Student) session.getAttribute("user");
		if (stu != null) {
			session.removeAttribute("user");
			curStu = null;
			return "index";
		}
		return "index";
	}

	@RequestMapping("/curUser")
	@ResponseBody
	public Student curSession(HttpServletRequest request) {

		try {
			System.out.println(request.hashCode());
			HttpSession session = request.getSession();
			// System.out.println("*** Session data ***");
			// Enumeration<String> e = session.getAttributeNames();
			// while (e.hasMoreElements()) {
			// String s = e.nextElement();
			// System.out.println(s + " == " + session.getAttribute(s));
			// }
			Student stu = (Student) session.getAttribute("user");
			if (stu != null) {
				return stu;
			} else {
				return curStu;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	/********************/
	public void setStuService(StudentDao stuService) {
		this.stuDao = stuService;
	}
}
